import axios, {AxiosRequestConfig, AxiosResponse} from 'axios';
import router from '../router';
import {message} from 'ant-design-vue';
import NProgress from "nprogress";

// 创建axios对象
const api = axios.create({
  baseURL: window.location.origin,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  },
  timeout: 10000
});

// 请求拦截
api.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 获取、添加token
    // const accessToken = sessionStorage.getItem('access_token');
    // if (accessToken) {
    //   config.headers.Authorization = accessToken;
    // }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);
//定义返回拦截
api.interceptors.response.use(
  (response: AxiosResponse) => {
    const data = checkServerStatus(response);
    if (data) return checkDataStatus(data);
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 格式化请求地址;
function renderUrlTemplate(method: string,url: string, params: any) {
  if (method==="get"){
    const tmp = url.replace(/{([^}]+)}/g, (m, p) => {
      const ret = params[p];
      delete params[p];
      return ret;
    });
    return `/api${tmp}`;
  }
  return `/api${url}`;
}

// get请求
export function rainbow_http_get(url: string, options: any,) {
  const newUrl = renderUrlTemplate("get", url, options);
  return api({url: newUrl, method: 'get', params: options});

}

// post请求
export function rainbow_http_post(url: string, options: any) {
  const newUrl = renderUrlTemplate("post", url, options);
  return api({url: newUrl, method: 'post', data: options});
}

// 检查服务器返回状态
function checkServerStatus(response: any) {
  if (response && response.status && response.status!==200) {
    message.error('服务器错误');
    throw new Error();
  }else {
    return response.data
  }
}

// 检查返回数据状态
function checkDataStatus(data: any) {
  if (data.state !== 200) {
    if (data.state === 300) {
      NProgress.done();
      router.push({ name: 'login' });
    } else {
      message.error(data.message || '未知错误');
      throw new Error();
    }
  }else {
    return data.data
  }
}
